<?php

namespace App\Admin\Forms\Good;

use App\Admin\Services\GoodService;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class ImportAsin extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = 'asin导入';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     * @throws IOException
     * @throws ReaderNotOpenedException
     */
    public function handle(Request $request)
    {
        $reader = ReaderEntityFactory::createCSVReader();
        $reader->open($request->file('file'));

        $sheets = $reader->getSheetIterator();
        $sheets->rewind();
        $sheet = $sheets->current();

        $total = $success = 0;
        set_time_limit(-1);
        foreach ($sheet->getRowIterator() as $k => $row) {
            $rowArr = $row->toArray();
            if (strlen($rowArr[4]) != 10) {
                continue;
            }

            if (strlen($rowArr[0]) < 3) {
                continue;
            }

            $total++;
            if (GoodService::importAsin($rowArr)) {
                $success++;
            }
        }
        $reader->close(); // 释放内存

        admin_toastr("表中一共{$total}个asin，成功操作{$success}个", "success", ['timeOut' => 5000]);
        return back();
    }

    /**
     * Build a form here
     */
    public function form()
    {
        $this->file('file', '请选择文件')
            ->rules('required', [
                'required' => '请选择上传文件',
                'mimes' => '请上传csv文件'
            ]);
    }

}
